package com.yupi.springbootinit.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author HJY_Maker
 * @Date 2024/5/14 星期二 21:00
 */

@Slf4j
public class ExcelUtils {
    /**
     * excel转csv
     *
     * @param multipartFile
     * @return
     */
    public static final String ExceltoCsv(MultipartFile multipartFile) {

        List<Map<Integer, String>> list = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //读取数据
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            log.error("表格处理错误/csv转换错误" + e.getMessage());
        }
        if (CollectionUtil.isEmpty(list)) {
            return "";
        }

        //转换成csv
        //读取表头
        LinkedHashMap<Integer, String> headMap = (LinkedHashMap) list.get(0);
        List<String> headList = headMap.values()
                .stream()
                .filter(ObjectUtils::isNotEmpty)
                .collect(Collectors.toList());//结果为 [日期，用户数]
//      List<String> headList = headMap.values().stream().filter(head -> ObjectUtils.isNotEmpty(head)).collect(Collectors.toList());
        //把list集合 利用StringBuilder拼接起来，其中用逗号隔开，最后再加个换行，以便后续查看结果容易看
        stringBuilder.append(StringUtils.join(headList, ',')).append("\n");
        //读取数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap) list.get(i);
            List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join("," + dataList, ',')).append("\n");
        }
        return stringBuilder.toString();
    }
}
